import 'package:get/get.dart';
import 'package:flutter/material.dart';
import 'package:getx_scaffold/common/index.dart';
import 'package:oramemo/core/repositories/default_api.dart';
import 'package:oramemo/entity/base_entity.dart';
import 'package:oramemo/pages/home/home_logic.dart';
import 'invsend_state.dart';

class InvsendLogic extends GetxController {
  final InvsendState state = InvsendState();
  final TextEditingController contactController = TextEditingController();
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();

  // 验证输入是否为有效的邮箱
  bool isValidEmail(String email) {
    final emailRegExp = RegExp(r'^[a-zA-Z0-9.]+@[a-zA-Z0-9]+\.[a-zA-Z]+');
    return emailRegExp.hasMatch(email);
  }

  // 验证输入是否为有效的手机号（简单验证）
  bool isValidPhone(String phone) {
    // 简单验证中国手机号，以86开头或不带国家代码
    if (phone.startsWith('86')) {
      phone = phone.substring(2);
    }
    final phoneRegExp = RegExp(r'^1[3-9]\d{9}$');
    return phoneRegExp.hasMatch(phone);
  }

  Future<void> _send(String userName) async {
    final deviceId = HomeLogic.to.currentDeviceId;
    BaseEntity? res = await DefaultApi()
        .oraDeviceUserCircleInvitePost<BaseEntity>(
            deviceId: deviceId, userName: userName);
    if (res?.isSuccess == true) {

      // 发送成功
      Get.back();
      Toast.show('邀请发送成功');
      // Get.snackbar(
      //   '邀请发送成功',
      //   '已向 $userName 发送邀请',
      //   snackPosition: SnackPosition.BOTTOM,
      //   backgroundColor: Colors.green,
      //   colorText: Colors.white,
      // );
    }
  }

  // 验证输入
  String? validateContact(String? value) {
    if (value == null || value.isEmpty) {
      return '请输入邮箱或手机号';
    }

    if (!isValidEmail(value) && !isValidPhone(value)) {
      return '请输入有效的邮箱或手机号';
    }

    return null;
  }

  // 发送邀请
  Future<void> sendInvitation() async {
    if (formKey.currentState?.validate() ?? false) {
      state.isLoading.value = true;

      try {
        // 根据输入类型确定发送方式
        final contact = contactController.text.trim();
        if (isValidEmail(contact)) {
          // 发送邮件邀请
          await _sendEmailInvitation(contact);
        } else if (isValidPhone(contact)) {
          // 发送短信邀请
          await _sendSmsInvitation(contact);
        }

      } catch (e) {
        Toast.show('邀请发送失败');
        // Get.snackbar(
        //   '邀请发送失败',
        //   '请稍后重试',
        //   snackPosition: SnackPosition.BOTTOM,
        //   backgroundColor: Colors.red,
        //   colorText: Colors.white,
        // );
      } finally {
        state.isLoading.value = false;
      }
    }
  }

  // 发送邮件邀请
  Future<void> _sendEmailInvitation(String email) async {
    _send(email);
  }

  // 发送短信邀请
  Future<void> _sendSmsInvitation(String phone) async {
    _send(phone);
  }

  @override
  void onClose() {
    contactController.dispose();
    super.onClose();
  }
}
